﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NexTrackDesktop.Media;
using System.Windows;
using System.Threading;

namespace NexTrackDesktop.NexTrack
{
    /// <summary>
    /// This class contains nextrack instance and communicates with web service
    /// </summary>
    public class Client : IClient
    {        
        public Client(MainServiceAdapter adapter)
        {
            WebService = adapter;

            ThumbnailCache = new ThumbnailCache();
            MediaLibrary = new Library(new FileNameTagger());

            Player = new NexTrackPlayer();
            Player.MediaEnded += new Action(Player_MediaEnded);
        }

        public virtual ThumbnailCache ThumbnailCache { get; set; }
        public virtual MainServiceAdapter WebService { get; set; }
        public virtual IParty Party { get; set; }
        public virtual ILibrary MediaLibrary { get; set; }
        public virtual NexTrackPlayer Player { get; set; }

        public virtual event Action PartyLoaded;
        public virtual event Action MusicStarting;

        /// <summary>
        /// This method loads the party related resources
        /// </summary>
        /// <param name="party">Party to load</param>
        public virtual void LoadParty(string PartyID, string Description, string AccessCode)
        {
            Party = new Party(PartyID, Description, AccessCode, WebService);

            if (PartyLoaded != null)
                PartyLoaded();

            ThreadStart t = new ThreadStart(() =>
                {
                    while (true)
                    {
                        System.Threading.Thread.Sleep(5000);
                        Party.Queue.UpdateQueue();
                    }
                });
            new Thread(t).Start();
        }

        /// <summary>
        /// This method starts the music for the party.
        /// </summary>
        public virtual void StartMusic()
        {
            if (MusicStarting != null)
                MusicStarting();

            NextSong();
        }

        /// <summary>
        /// When the media player's music has ended, we start a new song.
        /// </summary>
        private void Player_MediaEnded()
        {
            NextSong();
        }

        public virtual void NextSong()
        {
            Song s = WebService.GetNextSong();
            Player.NowPlaying = s;
            WebService.UpdateNowPlaying(s);
            Party.Queue.UpdateQueue();
        }

    }
}
